using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(CircleCollider2D))]
public class Turret : MonoBehaviour
{
    [SerializeField] public float attackRange = 3f; // 视为攻击范围
    private bool _gameStarted; // 游戏是否已经开始

    public Enemy CurrentEnemyTarget { get; set; }
    private List<Enemy> _enemies;

    public TurretUpgrade TurretUpgrade {get;set;}
    private void Start()
    {
        _gameStarted = true; // 设置游戏为已开始状态
        _enemies = new List<Enemy>();
        TurretUpgrade = GetComponent<TurretUpgrade>();
    }

    private void Update()
    {
        GetCurrentEnemyTarget();
        RotateTowardsTarget();
    }

    //获取当前敌人目标
    private void GetCurrentEnemyTarget()
    {
        if (_enemies.Count <= 0)
        {
            CurrentEnemyTarget = null;
            return;
        }
        CurrentEnemyTarget = _enemies[0];
    }

    //面向敌人
    private void RotateTowardsTarget()
    {
        if (CurrentEnemyTarget == null) return;
        Vector3 targetPos = CurrentEnemyTarget.transform.position - transform.position;
        float angle = Vector3.SignedAngle(transform.up, targetPos, transform.forward);
        transform.Rotate(0f, 0f, angle);
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Enemy"))
        {
            Enemy newEnemy = other.GetComponent<Enemy>();
            _enemies.Add(newEnemy);
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Enemy"))
        {
            Enemy enemy = other.GetComponent<Enemy>();
            if (_enemies.Contains(enemy))
            {
                _enemies.Remove(enemy);
            }
        };
    }


    private void OnDrawGizmos()
    {
        if (!_gameStarted)
        {
            // 在Scene视图中绘制攻击范围的可视化表示
            GetComponent<CircleCollider2D>().radius = attackRange; // 设置CircleCollider2D的半径为攻击范围
            Gizmos.DrawWireSphere(transform.position, attackRange); // 在指定位置绘制表示攻击范围的线框球体
        }
    }
}
